import tkinter as tk
from tkinter import ttk, messagebox
import logging

def add_record_dialog(root, current_ledger, refresh_table):
    dialog = tk.Toplevel(root)
    dialog.title("添加新记录")

    fields = [
        ('姓名', 'name'),
        ('金额', 'amount'),
        ('关系', 'relationship'),
        ('场合', 'occasion'),
        ('备注', 'notes')
    ]

    entries = {}
    for i, (label, key) in enumerate(fields):
        ttk.Label(dialog, text=label + ":").grid(row=i, column=0, padx=5, pady=5, sticky=tk.E)
        entry = ttk.Entry(dialog)
        entry.grid(row=i, column=1, padx=5, pady=5)
        entries[key] = entry

    def save_record():
        data = {}
        try:
            for key, entry in entries.items():
                value = entry.get()
                if key == 'amount':
                    value = float(value)
                data[key] = value

            current_ledger.add_record(data)
            refresh_table()
            dialog.destroy()
            messagebox.showinfo("成功", "记录添加成功！")
            logging.info("Successfully added a new record")
        except ValueError:
            messagebox.showerror("错误", "金额必须为数字")
            logging.error("Failed to add a new record: Amount must be a number")

    ttk.Button(dialog, text="保存", command=save_record).grid(row=len(fields), columnspan=2, pady=10)

def edit_record_dialog(root, current_ledger, refresh_table, record_id):
    original_data = next(r for r in current_ledger.records if r['id'] == record_id)
    dialog = tk.Toplevel(root)
    dialog.title("编辑记录")

    fields = [
        ('姓名', 'name'),
        ('金额', 'amount'),
        ('关系', 'relationship'),
        ('场合', 'occasion'),
        ('备注', 'notes')
    ]

    entries = {}
    for i, (label, key) in enumerate(fields):
        ttk.Label(dialog, text=label + ":").grid(row=i, column=0, padx=5, pady=5, sticky=tk.E)
        entry = ttk.Entry(dialog)
        entry.insert(0, original_data.get(key, ''))
        entry.grid(row=i, column=1, padx=5, pady=5)
        entries[key] = entry

    def update_record():
        new_data = {}
        try:
            for key, entry in entries.items():
                value = entry.get()
                if key == 'amount':
                    value = float(value)
                new_data[key] = value

            if current_ledger.update_record(record_id, new_data):
                refresh_table()
                dialog.destroy()
                messagebox.showinfo("成功", "记录更新成功！")
                logging.info(f"Successfully updated record with ID {record_id}")
        except ValueError:
            messagebox.showerror("错误", "金额必须为数字")
            logging.error(f"Failed to update record with ID {record_id}: Amount must be a number")

    ttk.Button(dialog, text="更新", command=update_record).grid(row=len(fields), columnspan=2, pady=10)